package com.module.app.base;

import android.content.Context;
import android.os.Handler;

import com.module.app.utils.AutoSkinNightUtils;
import com.module.app.utils.NetTimeUtils;
import com.module.app.bean.IType;
import com.module.base.base.IModuleApplication;
import com.module.base.cache.CacheSDK;
import com.module.base.utils.AppUtils;
import com.module.base.utils.ForegroundCallbacks;
import com.module.frame.app.AppManager;

/**
 * @author bsnl_yanxuwen
 * @date 2021/1/20 11:07
 * Description :
 * 这里不建议做初始化操作
 */
public class BaseApplication extends com.module.frame.base.BaseFrameApplication {

    //哪些模块需要初始化
    public static final String[] MODULESLIST = {
            "com.module.test.TestApplication",
            "com.privates.club.module.login.LoginApplication"};

    private volatile static BaseApplication instance;

    public static Context getContext() {
        return getInstance().getApplicationContext();
    }

    public static BaseApplication getInstance() {
        if (instance == null) {
            synchronized (BaseApplication.class) {
                if (instance == null) {
                    instance = new BaseApplication();
                }
            }
        }
        return instance;

    }

    public void onCreate() {
        super.onCreate();
        instance = this;

        modulesApplicationInit();
        AppUtils.syncIsDebug(getApplicationContext());
        Handler handler = new Handler();
        ForegroundCallbacks.get(this).addListener(new ForegroundCallbacks.Listener() {
            @Override
            public void onBecameForeground() {
                handler.removeCallbacksAndMessages(null);
                NetTimeUtils.Companion.onNetRectify();
                //检查系统是否是夜间模式
                AutoSkinNightUtils.followSystem();
            }

            @Override
            public void onBecameBackground() {
                boolean isError = CacheSDK.get(IType.ITemporaryCache.FLAG_ACTIVITY_BROUGHT_TO_FRONT, Boolean.class);
                if (isError) {
                    //当切换到后台的时候，强制关闭
                    AppManager.getInstance().AppExit();
                    return;
                }

            }
        });
    }

    /**
     * 模块初始化
     */
    private void modulesApplicationInit() {
        for (String moduleImpl : MODULESLIST) {
            try {
                Class<?> clazz = Class.forName(moduleImpl);
                Object obj = clazz.newInstance();
                if (obj instanceof IModuleApplication) {
                    ((IModuleApplication) obj).init();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ForegroundCallbacks.destroyed();
    }
}
